//
//  SinaWeibo+sendWeibo.m
//  Project_2_weibo
//
//  Created by 林林 on 16/7/7.
//  Copyright © 2016年 lhn. All rights reserved.
//

#import "SinaWeibo+sendWeibo.h"
#import "AFNetworking.h"
@class AFHTTPSessionManager;
#define UpdateURL @"https://api.weibo.com/2/statuses/update.json"       //发送纯文本
#define UploadURL @"https://api.weibo.com/2/statuses/upload.json"       //带图片微博

@implementation SinaWeibo (sendWeibo)

- (void)sendText:(NSString *)text
           image:(UIImage *)image
          params:(NSDictionary *)params
          sucess:(SendWeiboSuccessBlock)sBlock
            fail:(SendWeiboFailBlock)fBlock {
    
    //拼接参数
    NSMutableDictionary *mDic = [params mutableCopy];
    [mDic setObject:self.accessToken forKey:@"access_token"];
    [mDic setObject:text forKey:@"status"];
    
    //判断是否有图片
    if (image) {
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:UploadURL
           parameters:mDic
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    
    //将图片装换为NSData
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
    [formData appendPartWithFileData:imageData name:@"pic" fileName:@"image.jpg" mimeType:@"image/jpeg"];
}
              success:^(NSURLSessionDataTask *task, id responseObject) {
                  if (sBlock) {
                      sBlock(responseObject);
                  }
              }
              failure:^(NSURLSessionDataTask *task, NSError *error) {
                  if (fBlock) {
                      fBlock(error);
                  }
              }];
    } else {
        
        //发送不带图片的
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:UpdateURL
           parameters:mDic
              success:^(NSURLSessionDataTask *task, id responseObject) {
                  if (sBlock) {
                      sBlock(responseObject);
                  }
              }
              failure:^(NSURLSessionDataTask *task, NSError *error) {
                  if (fBlock) {
                      fBlock(error);
                  }
              }];
        
    }
    
    
    
}

@end
